var prefix = jsctx + "/orderInfo";

var orderInfo = (function () {
    function init() {
        setTimeout(function () {//防止先于-读取缓存执行
            load();
        }, 10)
    };

    $('#exampleTable').on('load-success.bs.table', function (e, data) {
        if (data.total && !data.rows.length) {
            $('#exampleTable').bootstrapTable('selectPage').bootstrapTable('refresh');
        }
    });
    var h = $(window).height() - 120;

    function load() {

        var userTenantCode = $("#userTenantCode").val();
        $('#exampleTable')
            .bootstrapTable(
                {
                    method: 'get',
                    url: prefix + "/listOrderInfo",
                    iconSize: 'outline',
                    toolbar: '#exampleToolbar',
                    striped: false,
                    dataType: "json",
                    pagination: true,
                    singleSelect: false,
                    // pageSize: 10,
                    pageList: [10, 20, 30],
                    // pageList: [10],
                    pageNumber: 1,
                    sidePagination: "server",
                    paginationShowPageGo: true,
                    height: h,
                    rightFixedColumns: true,
                    showColumns: true,
                    // fixedNumber: 5,
                    // columns: columns,
                    // showPaginationSwitch:true,
                    queryParams: function (params) {
                        return {
                            limit: params.limit,
                            offset: (params.offset / params.limit) + 1,
                            orderNum: $("#orderNum").val().trim(),
                            startTime: $("#startTime").val().trim(),
                            endTime: $("#endTime").val().trim(),
                            operatorId: $("#operatorId").val().trim(),
                            mobile: $("#mobile").val().trim(),
                            epName: $("#epName").val().trim()
                        };
                    },
                    columns: [
                        {
                            checkbox: true, field: '', width: '50', align: 'left',

                        },
                        {
                            title: '#', field: '', width: '50', align: 'left',
                            formatter: function (value, row, index) {
                                return index + 1;
                            }
                        },
                        {field: 'orderNum', title: '订单号', width: '130', align: 'left'},
                        {field: 'inTradeNo', title: '交易流水号', width: '130', align: 'left'},
                        {
                            field: 'status', title: '订单状态', width: '100', align: 'left',
                            formatter: function (value, row, index) {
                                //订单状态(0:未充电,1:充电中,2:已结束充电 3:充电结算中 4.占位费结算 5.占位中) 默认0
                                if (value == '0') {
                                    return '<span >未充电</span>'
                                } else if (value == '1') {
                                    return '<span >充电中</span>'
                                } else if (value == '2') {
                                    return '<span >已结束充电</span>'
                                } else if (value == '3') {
                                    return '<span >充电结算中</span>'
                                } else if(value == '4'){
                                    return '<span >占位费结算</span>'
                                } else if(value == '5'){
                                    return '<span >占位中</span>'
                                } else if(value == '6'){
                                    return '<span >待结算状态</span>'
                                }
                            }
                        },
                        {field: 'chargeDate', title: '充电日期', width: '120', align: 'left'},
                        {field: 'gunNo', title: '充电枪编号', width: '120', align: 'left'},
                        {field: 'stationName', title: '站点名称', width: '120', align: 'left'},
                        {field: 'operatorName', title: '所属加盟商', width: '120', align: 'left'},
                        {field: 'nickname', title: '用户姓名', width: '120', align: 'left'},
                        {field: 'mobile', title: '手机号', width: '120', align: 'left'},
                        {field: 'carNum', title: '车牌', width: '120', align: 'left'},
                        {field: 'chargingPolicy', title: '充电方式', width: '100', align: 'left',
                            formatter: function (value, row, index) {
                                if (value == '0') {
                                    return '<span >自动充满</span>'
                                } else if (value == '1') {
                                    return '<span >按时间充满</span>'
                                } else if (value == '2') {
                                    return '<span >定金额</span>'
                                } else if (value == '3') {
                                    return '<span >按电量充满</span>'
                                }
                                //0 自动充满 1 按时间充满 2 定金额 3 按电量充满
                            }
                        },
                        /*{field: 'nickname', title: '会员名', width: '100', align: 'left'},
                        {field: 'mobile', title: '手机号', width: '100', align: 'left'},
                        {field: 'carNum', title: '车牌', width: '100', align: 'left'},*/
                        {field: 'startTime', title: '充电开始时间', width: '100', align: 'left'},
                        {field: 'endTime', title: '充电结束时间', width: '100', align: 'left'},
                        {field: 'timeStr', title: '充电时长', width: '100', align: 'left'},
                        {field: 'beginSoc', title: '充电开始SOC', width: '100', align: 'left'},
                        {field: 'soc', title: '充电结束SOC', width: '100', align: 'left'},
                        {field: 'totalPower', title: '充电电量<br>(度)', width: '100', align: 'right'},
                        {field: 'totalMoney', title: '充电金额<br>(元)', width: '100', align: 'right'},
                        {field: 'discountAmount', title: '优惠金额<br>(元)', width: '100', align: 'right'},
                        {field: 'discountName', title: '优惠方式', width: '100', align: 'left'/*,
                            formatter: function (value, row, index) {
                                if (value == '0') {
                                    return '<span >满减卷</span>'
                                } else if (value == '1') {
                                    return '<span >满减卷</span>'
                                } else if (value == '2') {
                                    return '<span >满折卷</span>'
                                } else if (value == '3') {
                                    return '<span >满折卷</span>'
                                } else if (value == '4') {
                                    return '<span >代金券</span>'
                                } else if (value == '5') {
                                    return '<span >生日免单</span>'
                                } else if (value == '6') {
                                    return '<span >生日礼遇减免</span>'
                                } else if (value == '7') {
                                    return '<span >会员优惠</span>'
                                } else if (value == '8') {
                                    return '<span >权益金</span>'
                                } else if (value == '9') {
                                    return '<span >企业优惠</span>'
                                }
                            }*/
                        },
                        {field: 'payAmount', title: '实付金额', width: '100', align: 'left'},
                        {field: 'occupyPayTime', title: '支付时间', width: '100', align: 'left'},
                        {field: 'accountType', title: '支付方式', width: '100', align: 'left',
                            formatter: function (value, row, index) {
                                if (value == '0') {
                                    return '<span >个人钱包</span>'
                                } else if (value == '1') {
                                    return '<span >企业钱包</span>'
                                } else if (value == '2') {
                                    return '<span >共享余额</span>'
                                } else if (value == '3') {
                                    return '<span >先付后退钱包</span>'
                                }
                            }
                         },

                        {field: 'stopMsg', title: '充电结束说明', width: '100', align: 'right'},
                        {field: 'createdTime', title: '创建时间', width: '200', align: 'right'},
                        {
                            title: '操作',
                            field:
                                'operate',
                            width:
                                '150',
                            align:
                                'center',
                            class:
                                'operate-td',
                            formatter:

                                function (value, row, index) {
                                    var a = '<a  class="btn btn-success btn-sm ' + has_edit + '" href="#" title="订单详情" onclick="orderInfo.orderContent(\''
                                        + row.orderId
                                        + '\')">订单详情</a> ';
                                    return a;
                                    /*if (row.status!='2'){
                                        var a = '<a class="operateIcon stopIcon fl' + has_edit + '" href="#" title="结束订单" onclick="orderInfo.stopOrderInfo(\''
                                            + row.orderId
                                            + '\')"></a> ';

                                        var b = '<a class="operateIcon printerIcon' + has_edit + '" href="#" title="打印小票" onclick="orderInfo.printReceipt(\''
                                            + row.orderId
                                            + '\')"></a> ';


                                        return a + b + c ;
                                    }else {
                                        var a = '<a class="operateIcon stopIcon fl' + has_edit + '" href="#" title="结束订单" onclick="orderInfo.stopOrderInfo(\''
                                            + row.orderId
                                            + '\')"></a> ';

                                        var b = '<a class="operateIcon printerIcon' + has_edit + '" href="#" title="打印小票" onclick="orderInfo.printReceipt(\''
                                            + row.orderId
                                            + '\')"></a> ';
                                        var c = '<a class="operateIcon detailIcon ' + has_edit + '" href="#" title="订单详情" onclick="orderInfo.orderContent(\''
                                            + row.orderId
                                            + '\')"></a> ';
                                        var d = '<a class="operateIcon exceptionIcon fr' + has_edit + '" href="#" title="异常修复" onclick="orderInfo.addExceptionOrderInfo(\''
                                            + row.orderId
                                            + '\')"></a> ';
                                        return a+b+c+d;
                                    }*/
                                }
                        }
                    ],
                })
        ;
    }


    /**
     * 导出列表
     */
    function exportList() {
        $.fileDownload(prefix + "/export", { // 后台请求链接
            httpMethod: "get",　　　　　　　　// 请求方式
            contentType: 'application/json',　 // 请求头
            data: {　　　　　　　　　　　　　　　// 参数，左边为后台接收的参数名，右边为前端获取的值，
                offset: $('.active .page-link').text(),
                limit: $(".page-size").text(),
                orderNum: $("#orderNum").val().trim(),
                startTime: $("#startTime").val().trim(),
                endTime: $("#endTime").val().trim(),
                operatorId: $("#operatorId").val().trim(),
                mobile: $("#mobile").val().trim(),
                epName: $("#epName").val().trim()
            },
            prepareCallback: function (url) {
                layer.msg("文件下载中...", {time: -1})
            },
            abortCallback: function (url) {
                // 异常终止
                layer.msg("文件下载异常！！");
            },
            successCallback: function (url) {
                layer.msg("文件下载成功！！", {time: 1500});
            },
            failCallback: function (data) {
                var str = "{" + data.substring(data.indexOf("{") + 1, data.indexOf("}")) + "}";
                layer.msg(JSON.parse(str).message);
            }
        })
    }

    /**
     * 导出列表
     */
    function deletesBtn() {
        //debugger
        var rows = $("#exampleTable").bootstrapTable('getSelections');// 获得要删除的数据
        if (rows.length == 0) {// rows 主要是为了判断是否选中，下面的else内容才是主要
            return;
        } else {
            var ids = "";// 声明一个数组
            $(rows).each(function() {// 通过获得别选中的来进行遍历
                ids+= ","+this.orderId;// cid为获得到的整条数据中的一列
            });
            //debugger
            layer.confirm('确定删除选中的订单吗？', {
                btn: ['确定', '取消']
            }, function (index) {
                $.ajax({
                    url: prefix + "/deleteOrderIds",
                    type: "post",
                    data: {
                        'orderIds': ids
                    },
                    success: function (data) {
                        layer.close(index);
                        if (data.status == 200) {
                            layer.msg("删除成功");
                            reLoad();
                        } else {
                            layer.msg(data.message);
                        }
                    }
                });
            })
        }
    }

    function stopOrderInfo(orderId) {
        layer.confirm('确定要结束选中的订单(结束后用户订单将直接被结算)？', {
            btn: ['确定', '取消']
        }, function (index) {
            $.ajax({
                url: prefix + "/stopOrderInfo",
                type: "post",
                data: {
                    'orderId': orderId
                },
                success: function (data) {
                    layer.close(index);
                    if (data.status == 200) {
                        layer.msg("结束成功");
                        reLoad();
                    } else {
                        layer.msg(data.message);
                    }
                }
            });
        })

    }

    function printReceipt(orderId) {
//  $("#recipient-name").val(sort)
        //  $("#ulId").val(ulId)
        $('#exampleModal').modal('show')

        $("#savePrintReceipt").unbind("click").bind("click", function () {

            var formData = new FormData();
            formData.append("carNum", $("#saveCarNum").val());
            formData.append("orderId", orderId);
            $.ajax({
                url: prefix + "/savePrintReceipt",
                type: "post",
                data: formData,
                dataType: "json",
                processData: false, // 告诉jQuery不要去处理发送的数据，用于对data参数进行序列化处理 这里必须false
                contentType: false, // 告诉jQuery不要去设置Content-Type请求头
                success: function (data) {
                    if (data.status == 200) {
                        parent.layer.msg("操作成功");
                        $('#exampleModal').on('hidden.bs.modal', function () {
                            document.getElementById("contentForm").reset();
                        })
                        $('#exampleModal').modal('hide')
                        reLoad();
                    } else {
                        parent.layer.alert(data.message);
                        $('#exampleModal').on('hidden.bs.modal', function () {
                            document.getElementById("contentForm").reset();
                        })
                        //  $('#exampleModal').modal('hide')
                    }

                }
            })
        })

        $("#resetPrintReceipt").unbind("click").bind("click", function () {

            var formData = new FormData();
            formData.append("carNum", $("#carNum").val());
            formData.append("orderId", orderId);
            $.ajax({
                url: prefix + "/resetPrintReceipt",
                type: "post",
                data: formData,
                dataType: "json",
                processData: false, // 告诉jQuery不要去处理发送的数据，用于对data参数进行序列化处理 这里必须false
                contentType: false, // 告诉jQuery不要去设置Content-Type请求头
                success: function (data) {
                    if (data.status == 200) {
                        parent.layer.msg("操作成功");
                        $('#exampleModal').on('hidden.bs.modal', function () {
                            document.getElementById("contentForm").reset();
                        })
                        $('#exampleModal').modal('hide')
                        reLoad();
                    } else {
                        parent.layer.alert(data.message);
                        $('#exampleModal').on('hidden.bs.modal', function () {
                            document.getElementById("contentForm").reset();
                        })
                        //  $('#exampleModal').modal('hide')
                    }

                }
            })
        })


        // $("#giftMember").click(function () {
        //
        //
        // })
    }

    function reLoad() {
        var startTime = $("#startTime").val();
        $(".fixed-table-header-columns").css("display", "none");
        $(".fixed-table-body-columns").css("display", "none");
        $('#exampleTable').bootstrapTable('refresh');
    }

    function goBack() {
        location.href = prefix + "/index";
    }

    //订单详情
    function orderContent(orderId) {
        location.href = prefix + "/orderContent/" + orderId;
    }

    //异常订单数据修复登记
    function addExceptionOrderInfo(orderId) {
        // $('#exampleModal1').modal('show')
        //打开模态框垂直居中显示
        $('#exampleModal1').on('show.bs.modal', function(){
            var $this = $(this);
            var $modal_dialog = $this.find('.modal-dialog');
            $this.css('display', 'block');
            $modal_dialog.css({'margin-top': Math.max(0, ($(window).height() - $modal_dialog.height()) / 2) });

        });

        $("#exampleModal1").modal({keyboard: false});
        //原订单实付
        var hisPayAmount;

        $.ajax({
            url: prefix + "/selectOrderInfo",
            type: "get",
            data: {
                'orderId': orderId
            },
            success: function (data) {
                hisPayAmount=data.data.payAmount;
                $("#startTime1").val(data.data.startTime);
                $("#endTime1").val(data.data.endTime);
                $("#totalPower").val(data.data.totalPower);
                $("#elecMoney").val(data.data.totalElecMoney);
                $("#serviceMoney").val(data.data.totalSeviceMoney);
                $("#discountAmount").val(data.data.discountAmount);
                $("#totalMoney1").val(data.data.totalMoney);
                $("#payAmount").val(data.data.payAmount);
                $("#beginSoc").val(data.data.beginSoc);
                $("#soc").val(data.data.soc);
                $("#elecStationId").val(data.data.elecStationId);
            }
        })
        $("#payAmount").blur(function () {
            $("#diffPayAmount").val(parseFloat(parseFloat(hisPayAmount)-parseFloat($("#payAmount").val())).toFixed(2));
        });
        $("#submitData").unbind("click").bind("click", function () {

            var formData = new FormData();
            formData.append("orderId",orderId);
            formData.append("startTime", $("#startTime1").val());
            formData.append("endTime", $("#endTime1").val());
            formData.append("elecStationId", $("#elecStationId").val());
            formData.append("totalPower", $("#totalPower").val());
            formData.append("totalElecMoney", $("#elecMoney").val());
            formData.append("totalServiceMoney", $("#serviceMoney").val());
            formData.append("discountAmount", $("#discountAmount").val());
            formData.append("totalMoney", $("#totalMoney1").val());
            formData.append("payAmount", $("#payAmount").val());
            formData.append("beginSoc", $("#beginSoc").val());
            formData.append("soc", $("#soc").val());
            formData.append("solution", $("#solution").val());
            $.ajax({
                url: jsctx + "/exceptionOrder/saveExceptionOrderInfo",
                type: "post",
                data: formData,
                dataType: "json",
                processData: false, // 告诉jQuery不要去处理发送的数据，用于对data参数进行序列化处理 这里必须false
                contentType: false, // 告诉jQuery不要去设置Content-Type请求头
                success: function (data) {
                    if (data.status == 200) {
                        parent.layer.msg("操作成功");
                        $('#exampleModal1').on('hidden.bs.modal', function () {
                            document.getElementById("contentForm1").reset();
                        })
                        $('#exampleModal1').modal('hide')
                        reLoad();
                    } else {
                        parent.layer.alert(data.message);
                        $('#exampleModal1').on('hidden.bs.modal', function () {
                            document.getElementById("contentForm1").reset();
                        })
                        //  $('#exampleModal').modal('hide')
                    }

                }
            })
        });
        $("#cancel").unbind("click").bind("click", function () {
            document.getElementById("contentForm1").reset();
            $('#exampleModal1').modal('hide')
            reLoad();
        });
    }


    return {
        init: init,
        goBack: goBack,
        reLoad: reLoad,
        orderContent: orderContent,
        stopOrderInfo: stopOrderInfo,
        printReceipt: printReceipt,
        exportList: exportList,
        deletesBtn: deletesBtn,
        addExceptionOrderInfo: addExceptionOrderInfo
    };


})();
